package com.itjeffrey.autocode.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义日志打印线程池
 * 每次有任务提交线程池时打印线程池相关信息，包括但不限于任务总数、已完成数、活跃线程数、队列大小等等
 * @From: Jeffrey
 * @Date: 2021/6/5
 */
@Slf4j
public class LoggerThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {

    /**
     * 打印线程池日志
     */
    public void printThreadPoolLog(String prefix){
        ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();
        if(Objects.isNull(threadPoolExecutor)){
            return;
        }
        log.info("{}, {}, taskTotals:{}, completedTaskCounts:{}, activeThreadCount:{}, queueSize:{}",
                this.getThreadNamePrefix(),
                prefix,
                threadPoolExecutor.getTaskCount(),
                threadPoolExecutor.getCompletedTaskCount(),
                threadPoolExecutor.getActiveCount(),
                threadPoolExecutor.getQueue().size());
    }

    @Override
    public void execute(Runnable task) {
        printThreadPoolLog("2-execute-task");
        super.execute(task);
    }

    @Override
    public void execute(Runnable task, long startTimeout) {
        printThreadPoolLog("1-execute-task");
        super.execute(task, startTimeout);
    }

    @Override
    public Future<?> submit(Runnable task) {
        printThreadPoolLog("2-submit-task");
        return super.submit(task);
    }

    @Override
    public <T> Future<T> submit(Callable<T> task) {
        printThreadPoolLog("1-submit-task");
        return super.submit(task);
    }

    @Override
    public ListenableFuture<?> submitListenable(Runnable task) {
        printThreadPoolLog("2-submitListenable-task");
        return super.submitListenable(task);
    }

    @Override
    public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
        printThreadPoolLog("1-submitListenable-task");
        return super.submitListenable(task);
    }
}
